package com.edu.dao.impl;

import com.edu.bean.User;
import com.edu.dao.BaseDao;
import com.edu.dao.UserDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/*
 * @Author:mx
 * @Date:2025/9/19-14:48:37
 */
public class UserDaoImpl implements UserDao {

    @Override
    public User findUserByName(String name) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet res = null;
        User user = null;
        try {
            con = BaseDao.getConnection();
            String sql = "select * from user where username=?";
            ps = con.prepareStatement(sql);
            ps.setString(1, name);
            res = ps.executeQuery();
            if (res.next()) {
                user = new User(res.getInt("userId"), res.getString("username"), res.getString("password"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            BaseDao.close(res, ps, con);
        }
        return user;
    }

    @Override
    public User findUserByNameAndPwd(String name, String pwd) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet res = null;
        User user = null;
        try {
            con = BaseDao.getConnection();
            String sql = "select * from user where username=? and password=?";
            ps = con.prepareStatement(sql);
            ps.setString(1, name);
            ps.setString(2,pwd);
            res = ps.executeQuery();
            if (res.next()) {
                user = new User(res.getInt("userId"), res.getString("username"), res.getString("password"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            BaseDao.close(res, ps, con);
        }
        return user;
    }
}
